#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <syslog.h>
#include <errno.h>
#include <signal.h>
#include <sys/time.h>

#define FNAME		"/tmp/out"

static int daemonize(void)
{
	int fd;
	pid_t pid;

	pid = fork();
	if(pid < 0)
	{
		syslog(LOG_ERR,"fork():%s",strerror(errno));
		return -1;
	}

	if(pid > 0)
		exit(0);

	// child
	
//	close(0);
//	close(1);
//	close(2);
	sigset_t set;
	sigemptyset(&set);
	sigaddset(&set,SIGALRM);
	sigprocmask(SIG_BLOCK,&set,NULL);
	//sigprocmask(SIG_SETMASK,&set,NULL);
	struct itimerval itv;
	itv.it_interval.tv_sec=1;
	itv.it_interval.tv_usec=0;
	itv.it_value.tv_sec=1;
	itv.it_value.tv_usec=0;
	setitimer(ITIMER_REAL,&itv,NULL);
	fd = open("/dev/null",O_RDWR);
	if(fd < 0)
	{
		syslog(LOG_WARNING,"open():%s",strerror(errno));	
	}
	else
	{
		dup2(fd,0);
		dup2(fd,1);
		dup2(fd,2);
		if(fd > 2)
			close(fd);
	}
	
	setsid();

	chdir("/");
	umask(0);


	return 0;	
}

void alrm_sa(int s,siginfo_t *info,void *unused)
{
	FILE * fd = fopen("/tmp/out2","a");
//	while(1)
//	{
		fprintf(fd,"pid==%d\n",getpid());
		fflush(fd);
//		sleep(1);
//	}
}

int main()
{
	FILE *fp;
	int i;
	struct sigaction sa;
	
	openlog("mydaemon",LOG_PID,LOG_DAEMON);	
	
	sigemptyset(&sa.sa_mask);
	sigprocmask(SIG_UNBLOCK,&sa.sa_mask,NULL);
	sigaddset(&sa.sa_mask,SIGALRM);
	sa.sa_flags=SA_SIGINFO;
	sa.sa_sigaction=alrm_sa;
	sigaction(SIGALRM,&sa,NULL);
	struct itimerval itv;
	itv.it_interval.tv_sec=1;
	itv.it_interval.tv_usec=0;
	itv.it_value.tv_sec=1;
	itv.it_value.tv_usec=0;
	setitimer(ITIMER_REAL,&itv,NULL);
//	int i=0;
	for(i=0;i<3;i++)
	{
		pause();
		sleep(2);
	}
	if(daemonize() != 0)
		syslog(LOG_ERR,"daemonize() failed.");
	else
		syslog(LOG_INFO,"daemonize() successed.");

	/*do sth*/
	
	fp = fopen(FNAME,"w");
	if(fp == NULL)
	{
		syslog(LOG_ERR,"fopen():%s",strerror(errno));
		exit(1);
	}

	syslog(LOG_DEBUG,"%s was opened.",FNAME);

	for(i = 0 ; ; i++)
	{
		fprintf(fp,"%d\n",i);	
		sleep(1);
		fflush(fp);
		syslog(LOG_DEBUG,"%d was printed.",i);
	}
		
	fclose(fp);
	closelog();

	exit(0);
}


